﻿using System;
using System.Collections.Generic;
using System.Text;
using NFinal.Action;
using System.IO;

namespace NFinal
{
    public enum ImageType
    {
        Jpeg,
        Png,
        Bmp,
        Gif,
        Webp
    }
    public class ImageResult : ActionResult
    {
        public Stream stream;
        public ImageResult(Stream stream,ImageType imageType)
        {
            this.stream = stream;
            switch (imageType)
            {
                case ImageType.Bmp:this.ContentType = "image/bmp"; break;
                case ImageType.Gif:this.ContentType = "image/gif";break;
                case ImageType.Png:this.ContentType = "image/png";break;
                case ImageType.Jpeg:this.ContentType = "image/jpeg";break;
                default:this.ContentType = "image/webp";break;
            }
        }
        public override void ExecuteResult<TContext, TRequest>(AbstractAction<TContext, TRequest> context)
        {
            context.SetResponseHeader(Constant.HeaderContentType, this.ContentType);
            this.stream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[512];
            int count = 0;
            while ((count = this.stream.Read(buffer, 0, 512)) > 0)
            {
                context.Write(buffer, 0, count);
            }
            if (this.ContentType?.Length > 0)
            {
                context.contentType = this.ContentType;
            }
            context.Close();
        }
    }
}
